package simulation;

import java.util.HashMap;
import java.util.Map;

public class minNumberOfFrogs {
    /**
     * HashMap
     * @param c
     * @return
     */
    public int minNumberOfFrogs(String c)
    {
        char[] croakOfFrogs = c.toCharArray();
        String t = "croak";
        int n = t.length();
        int[] hash = new int[n]; // 数组模拟哈希表
        Map<Character, Integer> index = new HashMap<>(); // [x, x这个字符对应的下标
        for(int i = 0; i < n; i++)
            index.put(t.charAt(i), i);
        for(char ch : croakOfFrogs)
        {
            if(ch == t.charAt(0))
            {
                if(hash[n - 1] != 0) hash[n - 1]--;
                hash[0]++;
            }
            else
            {
                int i = index.get(ch);
                if(hash[i - 1] == 0) return -1;
                hash[i - 1]--; hash[i]++;
            }
        }
        for(int i = 0; i < n - 1; i++)
            if(hash[i] != 0)
                return -1;

        return hash[n - 1];
    }

    /**
     * if-else way
     * @param croakOfFrogs
     * @return
     */
    public int minNumberOfFrogs1(String croakOfFrogs) {
        int[] hash = new int[127];
        String tem = "croak";
        for(int i = 0;i<croakOfFrogs.length();i++) {
            char index = croakOfFrogs.charAt(i);
            if(index == 'c') {
                if(hash['k'-'a'] >0){
                    hash['k'-'a']--;
                    hash[index-'a']++;
                }else {
                    hash[index-'a']++;
                }

            }

            if(index == 'r'){
                if(hash['c'-'a'] > 0) {
                    hash['c'-'a']--;
                    hash[index-'a']++;
                }else {
                    return -1;
                }
            }

            if(index == 'o'){
                if(hash['r'-'a'] > 0) {
                    hash['r'-'a']--;
                    hash[index-'a']++;
                }else {
                    return -1;
                }
            }
            if(index == 'a'){
                if(hash['o'-'a'] > 0) {
                    hash['o'-'a']--;
                    hash[index-'a']++;
                }else {
                    return -1;
                }
            }
            if(index == 'k'){
                if(hash['a'-'a'] > 0) {
                    hash['a'-'a']--;
                    hash[index-'a']++;
                }else {
                    return -1;
                }
            }
        }
        for(int i = 'a'-'a';i <'k'-'a';i++) {
            if(hash[i] != 0) {
                return -1;
            }
        }
        return hash['k'-'a'];
    }
}
